package org.gdstash.ui.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Vector;

public class WideComboBox<T> extends JComboBox<T> {
    private boolean layingOut;

    public WideComboBox() {
        super();
        init();
    }

    private void init() {
        this.layingOut = false;
        this.addItemListener(new ToolTipItemListener());
        this.setUI(new WideMetalComboBoxUI());
    }

    public WideComboBox(final T[] items) {
        super(items);
        init();
    }

    public WideComboBox(final Vector<T> items) {
        super(items);
        init();
    }

    public WideComboBox(final ComboBoxModel<T> aModel) {
        super(aModel);
        init();
    }

    @Override
    public void doLayout() {
        try {
            this.layingOut = true;
            super.doLayout();
        } finally {
            this.layingOut = false;
        }
    }

    /**
     * 条形标签
     *
     * @param s s
     * @return {@link String }
     * @author pengzhikang
     * @date 2025/01/21 13:14
     */
    private String stripTags(final String s) {
        StringBuilder newS = new StringBuilder();
        String remainder = s;
        for (int pos = remainder.indexOf("<"); pos != -1; pos = remainder.indexOf(">", pos), remainder = remainder.substring(pos + 1), pos = remainder.indexOf("<")) {
            newS.append(remainder, 0, pos);
}
        return newS.toString();
    }

    @Override
    public void setModel(ComboBoxModel<T> aModel) {
        super.setModel(aModel);
    }

    class ToolTipItemListener implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED && e.getItem() != null) {
                // 设置tooltip文本
                setToolTipText(e.getItem().toString());
            }
        }
    }

}
